<!--上传组件-->
<template>
  <el-upload
    ref="uploadRef"
    class="upload"
    drag
    action=""
    :auto-upload="false"
    :on-exceed="handleExceed"
    :on-change="handleChange"
    :file-list="fileList"
    :show-file-list="false"
    :limit="1"
    :http-request="upload"
  >
    <template #trigger>
      <el-button type="danger">选择本地文件</el-button>
    </template>
    <template #default>
      <el-button type="success"> <a :href="personnelImportTemplates">下载导入模板</a></el-button>
    </template>
  </el-upload>
</template>

<script setup>
import personnelImportTemplates from "@/assets/templateFile/人员导入模板.xlsx";
import { head } from "lodash";
import { ref } from "vue";
import { bulkImport } from "@/api/partyBuilding";
import { ElLoading, ElMessage, genFileId } from "element-plus";
const emit = defineEmits(["editGroup"]);
const fileList = ref([]); //文件列表
const uploadRef = ref(); //上传组件实列
const loadingInstance = ref(null); // loading实例
const props = defineProps({
  theCurrentGroupID: {
    type: String,
    required: true,
  },
}); //当前群组ID
/**
 * 自动覆盖上一个文件
 * @param files
 */
const handleExceed = files => {
  uploadRef.value.clearFiles();
  const file = head(files); //获取上传的文件,始终只有一个文件
  file.uid = genFileId();
  uploadRef.value.handleStart(file);
};
/**
 * 文件上传
 */
const handleChange = () => {
  uploadRef.value.submit();
};
const upload = async file => {
  const { theCurrentGroupID } = props;
  try {
    loadingInstance.value = ElLoading.service({ fullscreen: true, text: "文件上传中，请稍后" });
    const formData = new FormData();
    formData.append("id", theCurrentGroupID);
    formData.append("file", file.file);
    await bulkImport(formData); //上传文件
    ElMessage.success("文件上传成功");
  } catch (error) {
    //框架统一对catch里面已做处理 这里无需重复错误提示。
  } finally {
    loadingInstance.value.close();
    emit("editGroup", theCurrentGroupID);
  }
};
</script>

<style scoped lang="less">
.upload {
  display: flex;
  column-gap: 10px;
  flex-direction: row-reverse;
  justify-content: flex-end;
  :deep(.el-upload) {
    --el-upload-dragger-padding-horizontal: 0;
    --el-upload-dragger-padding-vertical: 0;
    .el-upload-dragger {
      border: none;
    }
  }
}
</style>
